<template>
  <div class="classAdmin">

    <div class="left">
      <!-- <el-input v-model="onSearch" style="width: 100%" placeholder="输入检索的关键字" prefix-icon="Search" /> -->
      <div class="classMenu">
        <el-tree node-key="id" :default-expanded-keys="expandedKeys" ref="treeRef" default-expand-all="true"
          @node-expand="onNodeExpand" @node-collapse="onNodeCollapse" :data="arch"
          :props="{ label: 'name', children: 'children' }" @node-click="handleNodeClick" class="treeStyle">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }} ({{ data.user_count }}人) </span>
            </span>
          </template>
        </el-tree>


      </div>
    </div>



    <div v-if="isShow" class="right">
      <div class="classHeader">
        <div class="top">
          <div class="className">
            <h2>{{ nodeName }}</h2>
            <span>{{ nodeNum }}人</span>
          </div>
          <div v-if="nodeId > 10" class="classInfo">
            <div @click="onClassTeacher" class="box">
              <el-icon>
                <View />
              </el-icon>
              <span> 班级老师</span>
            </div>
            <div @click="onEditClass" class="box">
              <el-icon>
                <Setting />
              </el-icon>
              <span>编辑班级</span>
            </div>
          </div>
        </div>
        <div v-if="nodeName != '未分组'" class="button">
          <el-button-group style="margin-bottom: 30px">
            <el-button @click="addUser" type="primary" icon="User">添加成员</el-button>
            <el-button @click="importUser">批量导入</el-button>

            <el-tooltip content="删除" placement="top">
              <el-popconfirm title='是否确认?' confirm-button-text='确认删除' @confirm='batchDel'>
                <template #reference>
                  <el-button :disabled="isDisabled">批量删除</el-button>
                </template>
              </el-popconfirm>
            </el-tooltip>


          </el-button-group>
          <!-- <div class="line"></div>
              <el-button @click="onJoin" style="margin-right: 10px;" >邀请加入</el-button>
              <el-badge @click="onApply" :value="12" class="item">
                <el-button >申请列表</el-button>
              </el-badge> -->
        </div>
      </div>
      <div class="classCon">
        <!-- 用户数据表格 -->
        <el-table v-loading="importUserload" element-loading-text="批量导入中..." :data="userList"
          @selection-change="handleSelectionChange" style="height: 75vh;  max-width: 100%; overflow:auto;">
          <el-table-column width="50px" type="selection" align="center" />
          <el-table-column width="200px" label="账号" align="left" prop="user_name" :show-overflow-tooltip="true">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <div class="block">
                  <el-avatar shape="square" :size="30" :src="squareUrl ? squareUrl : defAva" />
                </div>
                <span style="margin-left: 10px">{{
                  scope.row.user_name
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="100px" label="姓名" align="left" prop="nick_name" :show-overflow-tooltip="true">

          </el-table-column>
          <el-table-column width="200px" label="手机号码" align="left" prop="mobile" />
          <el-table-column width="200px" label="组织" align="left" key="arch_names" prop="arch_names"
            :show-overflow-tooltip="true" />
          <el-table-column width="100px" label="状态" align="left">
            <template #default="scope">
              <div style="
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                      padding-right: 30px;
                    ">


                <el-tag v-if="scope.row.join_time" class="ml-2" type="success">
                  <div style="display: flex; align-items: center">
                    <el-icon>
                      <Avatar />
                    </el-icon>
                  </div>
                </el-tag>
                <el-tag v-else class="ml-2" type="info">
                  <div style="display: flex; align-items: center">
                    <el-icon>
                      <Avatar />
                    </el-icon>
                  </div>
                </el-tag>

              </div>
            </template>
          </el-table-column>

          <el-table-column width="200px" label="加入时间" align="left" prop="join_time">
            <template #default="scope">
              <span>
                {{ parseTime(scope.row.join_time) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="200px" label="操作" align="left" class-name="small-padding fixed-width">
            <template #default="scope">
              <div v-if="nodeName == '未分组'">
                <el-tooltip content="修改" placement="top">
                  <el-button style="padding: 0 10px; height: 20px" @click="handleUpdate(scope.row)" type="primary"
                    icon="EditPen"></el-button>
                </el-tooltip>
              </div>
              <div v-else>
                <el-tooltip content="修改" placement="top">
                  <el-button style="padding: 0 10px; height: 30px" @click="handleUpdate(scope.row)" type="primary"
                    icon="EditPen"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-popconfirm title='是否确认删除?' confirm-button-text='确认删除' @confirm='handleDelUser(scope.row.user_id)'>
                    <template #reference>
                      <el-button style="padding: 0 10px; height: 30px" type="danger" icon="Delete"></el-button>
                    </template>
                  </el-popconfirm>
                </el-tooltip>
                <el-tooltip v-if="scope.row.cla_id" content="详情" placement="top">
                  <el-button style="padding: 0 10px; height: 30px" @click="handleDtail(scope.row.user_id)"
                    type="success" icon="Tickets"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="noUserCon" v-else>
      <el-empty :image-size="200" description="该分组暂无成员" />
    </div>

    <addUserDialog :nodeId="nodeId" :nodeName="nodeName" @addUserSuccess="addUserSuccess" :classData="classData"
      ref="userRef" />
    <teacherDialog v-if="nodeId" :nodeId="nodeId" ref="teachRef" />
    <editClassDialog @upClaSuccess="upClaSuccess" :arch_id="arch_id" :nodeId="nodeId" :marjor_id="marjor_id"
      :nodeName="nodeName" ref="editClassRef" />
    <AddClassDialog @addSuccess="addSuccess" :classId="classId" :arch="arch" ref="addClassRef" />
    <UserInfoDialog @upUserSuccess="upUserSuccess" :userData="userData" ref="userinfoRef" />
  </div>

  <!-- 批量导入弹出层 -->
  <el-dialog v-model="dialogVisible" title="批量导入" width="500">
    <div style="text-align: center; padding: 20px;">
      <p style="margin-bottom: 20px;">点击下方按钮下载表格文件格式：</p>
      <div style="width: 100px; height: 36px; background: #67C23A; margin: 0 auto; border-radius: 5px;">
        <a style=" color: #fff; display: flex; align-items: center; justify-content: center; line-height: 36px;  width: 100%; height: 100%;"
          :href="excelUrl" download> <el-icon>
            <Download />
          </el-icon>下载 Excel</a>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onConfirmImport">
          导入
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { parseTime } from "@/utils/ruoyi";
import { useFileSelector } from "@/utils/excel_util";
import useAppStore from '@/store/modules/app'
import addUserDialog from "@/components/addUserDialog.vue";
import teacherDialog from "@/components/teacherDialog.vue";
import editClassDialog from "@/components/editClassDialog.vue";
import AddClassDialog from "@/components/AddClassDialog.vue";
import UserInfoDialog from "@/components/UserInfoDialog.vue";
import defAva from "@/assets/images/user-default.jpg";
import { teachTree } from "@/api/admin/schoolTree";
import { classList } from "@/api/banji/classadmin";
import { userlist, deluser, tempUser } from "@/api/user";
import { onMounted } from "vue";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";
import { Download } from '@element-plus/icons-vue';
import { adduser } from "@/api/user";
import XLSX from 'xlsx-js-style';
const appStore = useAppStore()
const router = useRouter();
const userRef = ref(null);
const teachRef = ref(null);
const editClassRef = ref(null);
const addClassRef = ref(null);
const userinfoRef = ref(null);
const squareUrl = ref("");
const classData = ref([]);
const nodeName = ref(null);
const nodeNum = ref(null);
const nodeId = ref(null);
const marjor_id = ref(null)
const arch_id = ref(null)
const classId = ref(null);
const is_cla = ref(null);
const expandedKeys = ref(localStorage.getItem("expandedNodes") || []);
const userData = ref(null);
const userArray = ref([]);
const isShow = ref(false)
const isDisabled = ref(true)
const dialogVisible = ref(false)
const importUserload = ref(false)
const excelUrl = new URL('@/assets/xlsx/user.xlsx', import.meta.url).href;
// 班级列表参数
const classListData = ref({
  cla_name: "",
  page_size: "200",
  page_num: "1",
  for_me: true
});


onMounted(() => {
  if (appStore.sidebar.opened) {
    appStore.userbarW = 50
  } else {
    appStore.userbarW = 50
  }

})


// 对象树结构
const arch = ref([]);
// 用户列表
const userList = ref([]);

// 展开节点的处理函数
const onNodeExpand = (node) => {
  saveExpandedNodes(node.id);
};
// 折叠节点的处理函数
const onNodeCollapse = (node) => {
  delExpandedNodes(node.id);
};
// 保存展开节点到localStorage
const saveExpandedNodes = (nodeId) => {
  let expandedNodes = JSON.parse(localStorage.getItem("expandedNodes") || "[]");
  if (!expandedNodes.includes(nodeId)) {
    expandedNodes.push(nodeId);
  }
  localStorage.setItem("expandedNodes", JSON.stringify(expandedNodes));
};

// 折叠从localStorage删除节点
const delExpandedNodes = (nodeId) => {
  // 移除已关闭的节点
  let expandedNodes = JSON.parse(localStorage.getItem("expandedNodes") || "[]");
  const index = expandedNodes.indexOf(nodeId);
  if (index > -1) {
    expandedNodes.splice(index, 1);
  }
  localStorage.setItem("expandedNodes", JSON.stringify(expandedNodes));
};

// 添加成员
const addUser = () => {
  userRef.value.openDialog();
};
// 批量导入
const importUser = () => {
  dialogVisible.value = true
}


// 确定导入
const onConfirmImport = () => {
  dialogVisible.value = false
  useFileSelector({
    success: (file) => {
      console.log(file);
      importUserload.value = true
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result;
        // 使用 XLSX 来处理数据
        const workbook = XLSX.read(data, { type: 'binary' });
        // 获取第一个工作表的数据
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];
        const sheetData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        // 读取成功之后的数组
        let resultData = sheetData.slice(1);
        console.log(resultData);
        let newArray = resultData.map(item => {
          let obj = {
            username: item[0] ? item[0]+"" : "",
            password: item[1] ? item[1]+"" : "",
            mobile: item[2] ? item[2]+"" : "",
            nick_name: item.length > 3 ? item[3]+"" : '', // 如果存在第4项则赋值，否则为空字符串
            school_code: item.length > 4 ? item[4] + "" : '',  // 如果存在第5项则赋值，否则为空字符串
            is_cla: is_cla.value,
            class_info_id: nodeId.value + '',
            tenant_id: useUserStore().tenant_id
          };
          return obj;
        });

        console.log(newArray);

        // 将导入的数据添加到数据库
        let newArr = [];
let hasDuplicate = false;

newArray.forEach(e => {
    // 检查当前用户是否已存在
    const isDuplicate = userList.value.some(item => item.user_name === e.username);
    if (isDuplicate) {
        ElMessage.error(`用户 ${e.username} 已存在`);
        hasDuplicate = true;
        return; // 跳过当前用户，继续处理下一个
    }
    
    // 处理不重复的用户
    e.password = e.password ? e.password + '' : "";
    e.mobile = e.mobile ? e.mobile + '' : '';
    let data = {
        user: e
    };
    newArr.push(adduser(data));
});

// 如果有需要添加的用户
if (newArr.length > 0) {
    Promise.all(newArr).then((res) => {
        if (res[0] == '') {
            ElMessage.success("添加成功");
            importUserload.value = false;
            addUserSuccess();
        } else {
          const errorMessage = res[0]?.response?.data
          ElMessage.error(`添加失败：${errorMessage}`);
          addUserSuccess();
            importUserload.value = false;
        }
    });
} else if (hasDuplicate) {
    // 如果所有用户都是重复的
    ElMessage.warning("所有用户都已存在，请勿重复添加");
    addUserSuccess();
    importUserload.value = false;
} else {
    // 如果没有需要添加的用户
    ElMessage.warning("没有可添加的用户");
    addUserSuccess();
    importUserload.value = false;
}


        // 这里你可以进一步处理sheetData，比如设置到组件的data中或者用于其他用途
      };
      reader.readAsBinaryString(file);

    }
  })
}

// 班级老师
const onClassTeacher = () => {
  teachRef.value.openDialog();
};

// 编辑班级
const onEditClass = () => {
  editClassRef.value.classDialog = true;
};
/** 分组节点单击事件 */
function handleNodeClick(data) {
  if (data.parent_id == 0) {
    isShow.value = false
  } else {
    isShow.value = true
  }
  console.log(data);
  nodeName.value = data.name;
  nodeNum.value = data.user_count;
  nodeId.value = data.id;
  marjor_id.value = data.marjor_id,
    arch_id.value = data.arch_stu_group_id

  is_cla.value = data.is_cla ? data.is_cla : false;
  if (data.id == 1 || data.id == 4) {
    userList.value = []
    return
  }

  getUserList();
}


// // 申请列表
// const onApply = () => {
//   router.push({ path: "/system/applylist" })
// }

// 点击操作中的详情
const handleDtail = (id) => {
  router.push({ path: "/class/student", query: { user_id: id } });
};

// 邀请加入
// const onJoin = () => {
//   router.push({ path: "/system/join" })
// }
// 用户表格选择项发生变化时
const handleSelectionChange = (e) => {
  userArray.value = e;
  if (e.length) {
    isDisabled.value = false
  } else {
    isDisabled.value = true
  }
};

// 获取班级列表
const getClassList = () => {

  classList(classListData.value).then((res) => {
    console.log(res)
    classData.value = res.list

  });
};





// 获取管理端树形结构
const getTeachTree = () => {
  teachTree().then((res) => {
    // 合并逻辑
    let combinedArr = [];
    // 遍历学院架构
    res.arch.forEach(college => {
      // 初始化children数组
      college.children = [];
      let totalCount = 0;

      // 遍历班级架构，查找属于该学院的班级
      res.cla_arch.forEach(cla => {
        college.children.push({
          id: cla.id,
          arch_stu_group_id: cla.college_arch_stu_group_id,
          name: cla.cla_name, // 注意这里修正了属性名以匹配目标数组结构
          user_count: cla.user_count,
          is_cla: cla.is_cla,
          marjor_id: cla.marjor_id

        });
        totalCount += cla.user_count;

      });

      // 更新学院的总人数
      college.user_count = totalCount;

      // 将处理后的学院对象添加到最终数组中
      combinedArr.push(college);
    });
    console.log(combinedArr);

    arch.value = combinedArr;

  });
};


// 修改一条用户信息
const handleUpdate = (user_data) => {
  userData.value = user_data;
  userinfoRef.value.openDialog()
};

// 获取用户列表
const getUserList = () => {
  let data = {
    page_size: "200",
    page_num: "1",
    is_cla: is_cla.value,
    arch_id: nodeId.value + "",
  };
  console.log(data);
  userlist(data).then((res) => {
    console.log(res);

    res.list.forEach((item) => {
      function splitString(str) {
        if (!str) return { arch_ids: [], cla_id: "", newStr: "" };

        // 按 || 分割不同的组
        const groups = str.split("||");
        let arch_ids = [];
        let cla_id = "";
        let names = [];

        groups.forEach(group => {
          // 解析每个组的数据
          const [typeInfo, id] = group.split(";").map(s => s.trim());
          const [type, name] = typeInfo.split(":").map(s => s.trim());

          if (type === "ARCH") {
            arch_ids.push(parseInt(id));
            names.push(name);
          } else if (type === "CLASS") {
            cla_id = id;
            names.push(name);
          }
        });

        return {
          arch_ids,
          cla_id,
          newStr: names.join(" / ")
        };
      }

      let result = splitString(item.arch_names);
      item.arch_id = result.arch_ids;
      item.cla_id = result.cla_id;
      item.arch_names = result.newStr;
    });
    userList.value = res.list;
    console.log(userList.value);

    nodeNum.value = userList.value.length
    let result = userList.value.find(
      (e) => e.user_name == useUserStore().userName
    );
    if (result) {
      result.join_time = useUserStore().loginTime;
    }
  });
};

// 班级添加成功返回的方法
const addSuccess = () => {
  const expandedNodes = JSON.parse(
    localStorage.getItem("expandedNodes") || "[]"
  );
  expandedKeys.value = expandedNodes;
  getTeachTree();
  getUserList();
};


// 修改班级成功

const upClaSuccess = () => {
  const expandedNodes = JSON.parse(
    localStorage.getItem("expandedNodes") || "[]"
  );
  expandedKeys.value = expandedNodes;
  getTeachTree();
  getUserList();
  getClassList()

}

// 用户更新成功返回的方法
const upUserSuccess = () => {

  const expandedNodes = JSON.parse(
    localStorage.getItem("expandedNodes") || "[]"
  );
  expandedKeys.value = expandedNodes;
  getTeachTree();
  getUserList();

};

// 用户添加成功返回的方法
const addUserSuccess = () => {
  console.log(nodeId.value);
  const expandedNodes = JSON.parse(
    localStorage.getItem("expandedNodes") || "[]"
  );
  expandedKeys.value = expandedNodes;
  nodeNum.value++;
  getTeachTree();
  getUserList();
};

// 删除用户
const handleDelUser = (user_id) => {
  deluser(user_id).then((res) => {
    console.log(res);
    if (!res) {
      ElMessage.success("删除成功");
      const expandedNodes = JSON.parse(
        localStorage.getItem("expandedNodes") || "[]"
      );
      expandedKeys.value = expandedNodes;
      getUserList();
      getTeachTree();

    } else {
      ElMessage.error(res.response.data);
    }
  });
};

// 批量删除用户
const batchDel = () => {
  var userIdArr = [];
  userArray.value.forEach((e) => {
    userIdArr.push(deluser(e.user_id));
  });

  Promise.all(userIdArr).then((res) => {
    const expandedNodes = JSON.parse(
      localStorage.getItem("expandedNodes") || "[]"
    );
    expandedKeys.value = expandedNodes;
    getUserList();
    getTeachTree();


    ElMessage.success("批量删除成功");
  });
};

onMounted(() => {

  getTeachTree();
  getClassList();

});
</script>

<style lang="scss" scoped>
.classAdmin {

  display: flex;

  .left {
    height: calc(100vh - 84px);
    border-right: 2px solid #eee;
    padding: 20px 10px 0 0;
    min-width: 250px;
    overflow: auto;
  }

  .right {
    padding-left: 50px;
    width: 100%;
    height: calc(100vh - 84px);
    overflow: hidden;

    .classHeader {
      .top {

        display: flex;
        justify-content: space-between;

        .className {
          display: flex;
          align-items: center;

          margin: 30px 0 20px 0;

          h2 {
            line-height: 1em;
            font-size: 18px;
            font-weight: 900;
          }

          span {
            font-size: 14px;
            display: block;
            border: 1px solid #23c3b8;
            border-radius: 5px;
            color: #23c3b8;
            margin-left: 5px;
            padding: 0 5px;
          }
        }

        .classInfo {
          display: flex;
          align-items: center;
          padding-right: 10px;

          .box {
            display: flex;
            align-items: center;
            margin-left: 30px;
            font-size: 12px;
            color: #1890ff;
            cursor: pointer;

            span {
              margin-left: 3px;
            }
          }
        }
      }

      .button {
        display: flex;
        align-items: center;

        .line {
          width: 1px;
          height: 15px;
          margin: 0 7px;
          background: #ccc;
        }
      }
    }

    .classCon {
      display: flex;
      /* 或使用 'grid' */
      width: 100%;
      height: calc(100vh - 240px);
    }

    .coloricon {
      font-size: 12px;
    }
  }

  .noUserCon {

    display: flex;
    width: 100%;
    justify-content: center;

  }
}
</style>

<style>
.classAdmin .treeStyle .el-tree-node__content {
  line-height: 4em;
  height: 40px;
}

.classAdmin .el-badge__content {
  padding: 2px;
  height: auto;
  font-size: 8px;
}

.classAdmin .el-table .el-table__header-wrapper th,
.classAdmin .el-table .el-table__fixed-header-wrapper th {
  background-color: rgba(0, 0, 0, 0) !important;
}

/* 去掉表格底部水平滚动条的灰色线条 */
.el-table--fit .el-table__inner-wrapper:before {
  width: 0;
}
</style>